package com.proximity.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.beoui.geocell.GeocellManager;
import com.beoui.geocell.model.Point;
import com.proximity.dto.UserDto;
import com.proximity.json.bean.User;
import com.proximity.json.bean.UserLocation;
import com.proximity.service.UserService;

@Controller
@RequestMapping("/json")
public class JsonController {

	@Autowired
	UserService userService;
	
    @ModelAttribute
    @RequestMapping(value="/location", method = RequestMethod.POST)
    public Collection<User> location(UserLocation location) throws IOException {
    	UserDto user = userService.find(location.getId());
    	user.setLatitude(location.getLatitude());
    	user.setLongitude(location.getLongitude());
    	user.setCells(GeocellManager.generateGeoCell(new Point(user.getLatitude(), user.getLongitude())));
    	userService.save(user);
    	
    	Collection<UserDto> owners = userService.findByLocation(location.getLatitude(), location.getLongitude(), location.getLatitudeSpan(), location.getLongitudeSpan());
    	Collection<User> output = new ArrayList<User>();
    	User out = null;
    	for (UserDto own : owners) {
    		if (!location.getId().equals(own.getId().getId())) {
    			out = new User();
        		out.setId(own.getId().getId());
        		out.setLatitude(own.getLatitude());
        		out.setLongitude(own.getLongitude());
        		output.add(out);
    		}
    	}
    	
    	return output; 
    }
    
    @ModelAttribute
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public Long save(UserDto user) throws IOException {
    	user.setCells(GeocellManager.generateGeoCell(new Point(user.getLatitude(), user.getLongitude())));
    	userService.save(user);
    	return user.getId().getId();
    }
    
}
